import { ElSubMenu, ElMenuItem } from 'element-plus'
import { unref } from 'vue'
import { useRenderMenuTitle } from './useRenderMenuTitle'
import { useDesign } from '@/hooks/web/useDesign'
import type { MenuItem } from '../Menu.vue'

const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('submenu')

const { renderMenuTitle } = useRenderMenuTitle()

export const useRenderMenuItem = (menuMode: 'vertical' | 'horizontal') => {
  const renderMenuItem = (menuItems: MenuItem[], parentPath = '/') => {
    // 验证输入数据
    if (!menuItems || !Array.isArray(menuItems) || menuItems.length === 0) {
      console.warn('renderMenuItem: 无效的菜单数据', menuItems)
      return null
    }

    return menuItems
      .filter((item) => {
        // 过滤隐藏的菜单项和无效项
        if (!item || typeof item !== 'object') {
          console.warn('renderMenuItem: 发现无效的菜单项', item)
          return false
        }
        return !item.hidden
      })
      .map((item) => {
        const hasChildren =
          item.children && Array.isArray(item.children) && item.children.length > 0

        // 构建菜单项的标识符
        const itemKey = item.path || item.url || item.id?.toString() || ''

        // 添加调试信息
        console.log('渲染菜单项:', {
          id: item.id,
          title: item.title,
          path: item.path,
          url: item.url,
          itemKey: itemKey,
          hasChildren: hasChildren
        })

        if (!hasChildren) {
          // 没有子菜单，渲染为菜单项
          return (
            <ElMenuItem key={item.id} index={itemKey} disabled={item.disabled} route={item.path}>
              {{
                default: () =>
                  renderMenuTitle({
                    title: item.title,
                    icon: item.icon
                  })
              }}
            </ElMenuItem>
          )
        } else {
          // 有子菜单，渲染为子菜单
          return (
            <ElSubMenu
              key={item.id}
              index={itemKey}
              teleported
              popperClass={unref(menuMode) === 'vertical' ? `${prefixCls}-popper--vertical` : ''}
            >
              {{
                title: () =>
                  renderMenuTitle({
                    title: item.title,
                    icon: item.icon
                  }),
                default: () => renderMenuItem(item.children!, itemKey)
              }}
            </ElSubMenu>
          )
        }
      })
      .filter(Boolean) // 过滤掉 null 值
  }

  return {
    renderMenuItem
  }
}
